import axios from 'axios';
import { useCounterStore } from '@/stores/counter'

const service = axios.create({
  baseURL: '/api', // 添加基础URL，避免重复写/api
  timeout: 5000
});

// 请求拦截器 - 统一添加token
service.interceptors.request.use(config => {
  const store = useCounterStore()
  if (store.token) {
    config.headers['token'] = `Bearer ${store.token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})


// 请求拦截器 - 统一添加token
service.interceptors.request.use(config => {
  const store = useCounterStore();
  if (store.token) {
    config.headers['token'] = `Bearer ${store.token}`;
  }
  // 针对文件上传请求，不强制设置Content-Type（axios会自动处理form-data）
  if (config.url.includes('upload')) {
    delete config.headers['Content-Type'];
  }
  return config;
}, error => {
  return Promise.reject(error);
});

// 原有接口保持不变...

// ============================== 新增图片上传方法 ==============================
/**
 * 单文件上传（图片）
 * @param {File} file - 上传的文件对象
 * @param {Function} onProgress - 上传进度回调函数（可选）
 * @returns {Promise} - 包含图片URL的Promise
 */
export const uploadImage = (file, onProgress) => {
  const formData = new FormData();
  formData.append('file', file); // 需与后端@RequestParam("file")对应

  return service({
    url: '/api/idle/upload/image', // 直接使用基础URL后的路径，无需重复/api
    method: 'POST',
    data: formData,
    // 支持上传进度监听（如显示进度条）
    onUploadProgress: (progressEvent) => {
      if (onProgress) {
        const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
        onProgress(percent);
      }
    }
  });
};

// 登录方法 
export const login = (data) => {
  return service({
    url: 'api/user/login', // 修正为正确的API路径，只需要一个/api前缀
    method: 'post',
    data
  });
};
// 注册方法 
export const register = (data) => {
  return service({
    url: 'api/user/register', // 修正为正确的API路径，只需要一个/api前缀
    method: 'post',
    data
  });
};
//通过userid获取用户信息
export const getUserInfo = (userId) => {
  return service({
    url: `api/user/get/${userId}`,
    method: 'get'
  })
  }
// 获取动态列表
// 获取广场动态
export const squarelist = (data) => {
  return service({
    url: 'api/square/list',
    method: 'get',
    params: data // GET请求使用params
  })
}

// 发布动态
export const publishDynamic = (data) => {
  return service({
    url: 'api/square/publish',
    method: 'post',
    data
  })
}

// 点赞动态
export const likeDynamic = (dynamicId) => {
  const store = useCounterStore()
  return service({
    url: `api/square/like/${dynamicId}`,
    method: 'post',
    headers: {
      'Authorization': `Bearer ${store.token}`
    }
  })
}

// 发表评论
export const addComment = (dynamicId, content) => {
  const store = useCounterStore()
  return service({
    url: `/api/api/square/comment/${dynamicId}`,
    method: 'post',
    headers: {
      'Authorization': `Bearer ${store.token}`
    },
    data: { content }
  })
}
//发布闲置物品
export const publishItem = (data) => {
  return service({
    url: 'api/idle/publish',
    method: 'post',
    data
  })
}
//获取闲置物品列表
export const itemlist = (data) => {
  return service({
    url: 'api/idle/list',
    method: 'get',
    params: data // GET请求使用params
  })
}
//获取闲置物品详情
export const itemDetail = (itemId) => {
  return service({
    url: `api/idle/get/${itemId}`,
    method: 'get'
  })
}
//删除闲置物品
export const deleteItem = (itemId) => {
  const store = useCounterStore()
  return service({
    url: `api/idle/delete/${itemId}`,
    method: 'delete',
    headers: {
      'Authorization': `Bearer ${store.token}`
    }
  })
}
//修改闲置物品
export const updateItem = (itemId, data) => {
  const store = useCounterStore()
  return service({
    url: `api/idle/update/${itemId}`,
    method: 'put',
    headers: {
      'Authorization': `Bearer ${store.token}`
    },
    data
  })
}